package com.work.saturn.assets;

import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.alibaba.android.arouter.facade.annotation.Route;
import com.alibaba.android.arouter.launcher.ARouter;
import com.alibaba.fastjson.JSON;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.BaseViewHolder;
import com.immo.libcommon.base.BaseFragment;
import com.immo.libcommon.constant.BaseUrl;
import com.immo.libcommon.constant.SharePreferenceKey;
import com.immo.libcommon.http.NetworkRequest;
import com.immo.libcommon.utils.FullyLinearLayoutManager;
import com.immo.libcommon.utils.SharePreferenceUtils;
import com.work.saturn.R;
import com.work.saturn.account.LoginActivity;
import com.work.saturn.bean.MessageEvent;
import com.work.saturn.bean.UserMsgBean;
import com.work.saturn.bean.UserMsgDataBean;
import com.immo.libcommon.constant.RouterUtil;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Objects;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;
import de.hdodenhof.circleimageview.CircleImageView;


/**
 * @author Administrator
 * @content 资产
 * @date 2018/7/10
 */
@Route(path = RouterUtil.ASSETS_FRAGMENT)
public class AssetsFragment extends BaseFragment {
    @BindView(R.id.assets_head)
    CircleImageView assetsHead;
    @BindView(R.id.assets_name)
    TextView assetsName;
    @BindView(R.id.assets_desc)
    TextView assetsDesc;
    Unbinder unbinder;
    @BindView(R.id.assets_list_title)
    LinearLayout mTitle;
    @BindView(R.id.assets_list_view)
    View mView;
    @BindView(R.id.assets_list)
    RecyclerView mList;
    @BindView(R.id.main_srl)
    SwipeRefreshLayout mRefresh;
    private boolean isPrepared = false;
    List<UserMsgDataBean> userMsgDataList;
    private String userId;
    private int isRefresh;

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable
            Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_assets, container, false);
        unbinder = ButterKnife.bind(this, view);
        isPrepared = true;
        lazyLoad();
        EventBus.getDefault().register(this);
        return view;
    }
    @SuppressWarnings("unused")
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void Event(MessageEvent messageEvent) {
        if (messageEvent.getMessage().equals("更新首页数据")) {
            getUserMsg();
        }
    }

    /**
     * 获取用户信息
     */
    private void getUserMsg() {
        new NetworkRequest((object, data) -> {
            if (object instanceof UserMsgBean) {
                UserMsgBean userMsgBean = (UserMsgBean) object;
                mRefresh.setRefreshing(false);
                if (userMsgBean.isSuccess()) {
                    assetsName.setText(userMsgBean.getPayload().getName());
                    assetsDesc.setText(userMsgBean.getPayload().getId());
                    userId = userMsgBean.getPayload().getId();
                    SharePreferenceUtils.put(Objects.requireNonNull(getActivity()), SharePreferenceKey.ID, userId);
                    userMsgDataList = new ArrayList<>();
                    try {
                        JSONObject obj = new JSONObject(data).getJSONObject("payload");
                        JSONObject walletJson;
                        if (obj.get("wallet").toString().length() != 0) {
                            walletJson = obj.getJSONObject("wallet");
                        } else {
                            mTitle.setVisibility(View.GONE);
                            mView.setVisibility(View.GONE);
                            return;
                        }
                        Iterator<String> sIterator = walletJson.keys();
                        while (sIterator.hasNext()) {
                            // 获得key
                            String key = sIterator.next();
                            String value = walletJson.getString(key);
                            Log.v("JsonTag____", value);
                            UserMsgDataBean skuDataBean = JSON.parseObject(value, UserMsgDataBean.class);
                            userMsgDataList.add(skuDataBean);
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                    initListData();
                }

            }
        }).requestGet(BaseUrl.GETUSERMSG + Objects.requireNonNull(SharePreferenceUtils.get(Objects.requireNonNull(getActivity()), SharePreferenceKey.USERNAME, "")).toString(),
                getActivity(), UserMsgBean.class, isRefresh == 0, false);
    }

    /**
     * 初始化列表数据
     */
    private void initListData() {
        FullyLinearLayoutManager linearLayoutManagerTheme = new FullyLinearLayoutManager(getActivity()) {
            @Override
            public boolean canScrollVertically() {
                return false;
            }
        };
        linearLayoutManagerTheme.setOrientation(LinearLayoutManager.VERTICAL);
        mList.setLayoutManager(linearLayoutManagerTheme);
        AssetsDetailAdapter releaseDetailAdapter = new AssetsDetailAdapter();
        //设置适配器
        releaseDetailAdapter.bindToRecyclerView(mList);
        mRefresh.setOnRefreshListener(() -> {
            isRefresh = 1;
            getUserMsg();

        });
    }

    @Override
    protected void lazyLoad() {
        if (!isPrepared || !isVisible) {
            return;
        }
        getUserMsg();
        isPrepared = false;
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        unbinder.unbind();
        if (EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().unregister(this);
        }
    }

    @OnClick(R.id.assets_code)
    public void onViewClicked() {
        ARouter.getInstance().build(RouterUtil.ASSETS_TURN_IN).withString("userId", userId).navigation();
    }


    /**
     * 资产列表
     */
    private class AssetsDetailAdapter extends BaseQuickAdapter<UserMsgDataBean, BaseViewHolder> implements BaseQuickAdapter.OnItemClickListener {
        AssetsDetailAdapter() {
            super(R.layout.item_assets, userMsgDataList);
            setOnItemClickListener(this);
        }

        @Override
        protected void convert(BaseViewHolder helper, UserMsgDataBean item) {
            helper.setText(R.id.assets_name, item.getSymbol());
            helper.setText(R.id.assets_num, "" + item.getAmount());
            helper.setText(R.id.assets_dw, item.getSymbol());

        }

        @Override
        public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
            ARouter.getInstance().build(RouterUtil.ASSETS_DETAIL_PAGE).
                    withSerializable("history", (Serializable) userMsgDataList.get(position).getHistory())
                    .withString("userId", assetsDesc.getText().toString())
                    .withString("symbol", userMsgDataList.get(position).getSymbol())
                    .withString("num", "" + userMsgDataList.get(position).getAmount())
                    .withString("name", "" + userMsgDataList.get(position).getSymbol())
                    .navigation();
        }
    }
}
